To learn JavaScript, we must learn the basics.
In this article, we’ll look at the most basic parts of the JavaScript language.
do…while Loops
We can use the do...while
loop to repeatedly run code.
The do
block is always run, so the first iteration is always run.
For example, we can write:
let i = 0;
do {
console.log(i);
i++;
} while (i <= 3);
The do
block is always run because the while
condition is checked after the iteration of a loop is done.
Script Tags
To run JavaScript code in the browser, we have to add script tags to our code.
For example, we can write:
<script>
function sayHi() {
alert("hi");
}
function sayBye() {
alert("bye");
}
</script>
We define the sayHi
and sayBye
functions in the script tag.
We can have any JavaScript code in our script tags.
JavaScript code is just text, so we can add them to HTML files easily, since they’re also text.
If we have lots of code in between the script tags, then we should move them to their own file.
For example, we can write:
<script src="script.js"></script>
We create a script.js
file and then reference it with the src
attribute.
This way, we can keep our code files short.
Comments
We can add comments to our JavaScript code to explain what we’re doing what our code.
For example, we can write:
// This is a comment
for (let i = 0; i < 10; i++) {
console.log(i);
}
The //
indicates the start of a comment. It’ll be ignored by the browser.
We can write multiline comments by writing:
/*
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at volutpat ipsum, dapibus tincidunt nisl. Donec vestibulum ultricies laoreet. Suspendisse sit amet faucibus justo.
*/
for (let i = 0; i < 10; i++) {
console.log(i);
}
We have a long comment that spans multiple lines. It’s delimited by /*
and */
.
Link Events
When we click links, we can listen to events emitted by the links when we do something to them like clicking it.
This is handy for using it to do something in addition to letting us click to go to a different page.
For example, we can write:
<a href="#" onClick="alert('hello');">Click</a>
We add the onClick
attribute to an a
tag so that we can run JavaScript code in it.
onClick
isn’t case sensitive.
href='#'
tells the browser to reload the page, which is probably not what we want when we want to run JavaScript code when we click the link.
To prevent the page from being refreshed, we can write:
<a href="javaScript:void(0)" onClick="alert('hello');">Click</a>
We add the javaScript.void(0)
code to avoid the refresh.
If we want to write multiple statements, we can write:
<a href="javaScript:void(0)" onClick="let greeting='hi'; alert(greeting);">Click</a>
We separate the statements with a semicolon.
Conclusion
We can use the do...while
loop to run a loop where the first iteration always runs.
Also, we can embed JavaScript in various ways within our HTML code.